<template>
	<view>
		<!-- 注册页 -->
		<view class="reg-view">
			<uni-forms ref="userFormRef" :model="userForm" :label-width="85" :rules="rules">
				<uni-forms-item label="头像">
					<button class="avatar" size="mini" type="default" open-type="chooseAvatar"
						@chooseavatar="chooseavatar">
						<image :src="avatar" mode=""></image>
					</button>
				</uni-forms-item>
				<uni-forms-item label="用户名" name="userName" required>
					<uni-easyinput v-model="userForm.userName" placeholder="用户名" />
				</uni-forms-item>
				<uni-forms-item label="密码" name="password" required>
					<uni-easyinput type="password" v-model="userForm.password" placeholder="密码" />
				</uni-forms-item>
				<uni-forms-item label="昵称" name="nickName" required>
					<uni-easyinput v-model="userForm.nickName" placeholder="昵称" />
				</uni-forms-item>
				<uni-forms-item label="班级" name="classId" required>
					<uni-data-picker v-model="userForm.classId" :localdata="classList" :fields="['text']" />
				</uni-forms-item>
				<uni-forms-item label="邮箱" name="email" required>
					<uni-easyinput v-model="userForm.email" placeholder="请输入你的邮箱" />
				</uni-forms-item>
				<uni-forms-item label="手机号码" name="phone" required>
					<uni-easyinput v-model="userForm.phone" placeholder="请输入11位数手机号码" />
				</uni-forms-item>
				<uni-forms-item label="性别" name="sex" required>
					<uni-data-checkbox v-model="userForm.sex" :localdata="sexs" />
				</uni-forms-item>
			</uni-forms>
			<!-- 注册按钮 -->
			<button type="primary" class="button-round" @tap="reg">注 册</button>
		</view>


	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
	} from 'vue';
	import fileApi from '@/api/file.js'
	import userApi from '@/api/user.js'
	import imageApi from '@/api/imageFile.js'
	import classesApi from '@/api/class.js'

	const userFormRef = ref()
	const userForm = ref({})
	const classList = ref([]); // 存储班级列表数据，格式为[{value: 班级ID, text: 班级名称}]
	const avatar = ref("/static/icon/avatar.png")

	onMounted(() => {
		// 在页面挂载时获取班级列表数据
		console.log('----Onload');
		classesApi.getClassList().then(res => {

			console.log('班级列表数据：', res.data);
			const classData = res.data.map(item => ({
				value: item.classesId, // 假设班级数据中班级编号的字段为id，根据实际情况修改
				text: item.classesName // 假设班级数据中班级名称的字段为name，根据实际情况修改
			}));
			classList.value = classData;
		}).catch(err => {
			console.log('获取班级列表出错：', err);
		});
	})

	const sexs = ref([{
			value: 0,
			text: '男'
		},
		{
			value: 1,
			text: '女'
		},
		{
			value: 2,
			text: '未知'
		}
	])

	const chooseavatar = (e) => {
		console.log("chooseavatar: ", e);
		imageApi.uploadFile(e.detail.avatarUrl).then(res => {
			avatar.value = e.detail.avatarUrl;
			const fileName = res.data.fileName

			// 根据文件名获取图片URL
			fileApi.getImageUrlByfileName(fileName).then(imgRes => {
				if (imgRes.code === 200) {
					console.log('获取图片URL成功', imgRes.data)
					userForm.value.avatar = imgRes.data
				} else {
					console.log('获取图片URL失败')
				}
			})

		});
	}

	const reg = () => {
		userFormRef.value.validate().then(res => {
			console.log('表单校验通过');
			userForm.value.status = 0 //普通注册用户
			console.log('表单信息------>', userForm.value)

			userApi.regUser(userForm.value).then(regRes => {
				uni.navigateTo({
					url: '/pages/reg/reg-success'
				})


			})
		}).catch(err => {
			console.log('表单错误信息：', err);
		})
	}
	// 注册校验规则
	const rules = {
		userName: {
			rules: [{
					required: true,
					errorMessage: '请输入用户名',
				},
				{
					minLength: 3,
					maxLength: 50,
					errorMessage: '用户长度在 {minLength} 到 {maxLength} 个字符',
				},
				//异步校验，判断用户名是否注册
				// {
				// 	validateFunction: (rule, value, data, callback) => {
				// 		// 异步需要返回 Promise 对象
				// 		return new Promise((resolve, reject) => {
				// 			userApi.countUserByuserName(value).then(res => {
				// 				if (res.data > 0) {
				// 					reject(new Error("该用户名已存在"))
				// 				}
				// 				resolve()
				// 			})
				// 		})
				// 	}
				// }
			]
		},
		password: {
			rules: [{
					required: true,
					errorMessage: '请输入密码',
				},
				{
					minLength: 6,
					maxLength: 20,
					errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
				}
			]
		},
		nickName: {
			rules: [{
					required: true,
					errorMessage: '请输入昵称',
				},
				{
					minLength: 2,
					maxLength: 50,
					errorMessage: '昵称长度在 {minLength} 到 {maxLength} 个字符',
				}
			]
		},
		classId: {
			rules: [{
				required: true,
				errorMessage: '请选择对应的班级',
			}]
		},
		email: {
			rules: [{
					required: true,
					errorMessage: '请输入你的邮箱',
				},
				{
					validateFunction: function(rule, value, data, callback) {
						const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
						if (!regex.test(value)) {
							callback("请输入正确的邮箱")
						}
						return true
					}
				}
			]
		},
		phone: {
			rules: [{
					required: true,
					errorMessage: '请输入手机号码',
				},
				{
					minLength: 11,
					maxLength: 11,
					errorMessage: '手机号码长度为11个字符',
				},
				{
					validateFunction: function(rule, value, data, callback) {
						const mobileRegex = /^1[3-9]\d{9}$/;
						if (!mobileRegex.test(value)) {
							callback("请输入正确的手机号码！")
						}
						return true
					}
				}
			]
		},
		sex: {
			rules: [{
				required: true,
				errorMessage: '请选中性别',
			}]
		},
	}
</script>


<style lang="scss">
	.reg-view {
		padding: 20px;

		.avatar {
			width: 56px;
			height: 56px;
			padding: 0;
			background-color: gray;
			border-radius: 28px;
			box-shadow: 0 0 5px gray;

			image {
				width: 56px;
				height: 56px;
			}
		}
	}

	.captcha-view {
		display: flex;
		justify-content: space-between;
	}
</style>